import Vue from 'vue'
import router from './router'
import store from './store'
import { ACCESS_TOKEN, OPRN_ID } from '@/store/mutation-types'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const globalQueryKeys = ['id']

NProgress.configure({ showSpinner: false })

const setWechatInfo = (from, to, next) => {
  const { query: { token, openId, redirect } } = to
  openId && Vue.ls.set(OPRN_ID, openId)
  token && store.dispatch('user/SetToken', token)
  next({ path: decodeURIComponent(redirect || '/'), replace: true })
}

const redirectWechatLogin = route => {
  const { origin } = window.location
  const callback = encodeURIComponent(origin + route.fullPath)
  window.location.href = `${process.env.VUE_APP_WX_LOGIN}?callback=${callback}`
}

const setGlobalQuery = query => {
  const result = {}
  for (const key in query) {
    if (globalQueryKeys.includes(key)) result[key] = query[key]
  }

  Object.keys(result).length > 0 && store.dispatch('route/SetQuery', result)
}

router.beforeEach((to, from, next) => {
  NProgress.start()

  const token = Vue.ls.get(ACCESS_TOKEN)
  const isWechat = store.getters.browser.indexOf('micromessenger') > -1

  setGlobalQuery(to.query)

  if (to?.meta?.login) {
    if (token) {
      next()
    } else {
      if (isWechat) {
        to.query.openId ? setWechatInfo(from, to, next) : redirectWechatLogin(to)
      } else {
        next({ name: 'login', query: { redirect: to.fullPath } })
      }
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})
